import Vue, { CreateElement, VNode } from 'vue';
import { Component, Prop } from 'vue-property-decorator';

import { ViewContextDescriptor, isFunction, getViews, createView } from '../../vendors/handie';

import { isComponentCtor } from '../../utils';
import { createModuleContext } from '../../adapters/context';

@Component({
  // @ts-ignore
  abstract: true,
})
export default class ViewRenderer extends Vue {
  @Prop({ type: String, default: '' })
  private readonly view!: string;

  @Prop({ type: Array, default: () => [] })
  private readonly params!: any[];

  private render(h: CreateElement): VNode | null {
    const [moduleName, resourceType, viewName] = this.view.split('.');
    const view = getViews(moduleName)[viewName];

    if (resourceType !== 'views' || !view) {
      return null;
    }

    return h(
      createView(
        createModuleContext(moduleName),
        isFunction(view) && !isComponentCtor(view)
          ? (view as (...args: any[]) => ViewContextDescriptor)(...this.params)
          : (view as ViewContextDescriptor),
      ),
    );
  }
}
